using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.UI;

public class DebugLogInterceptor : MonoBehaviour {
    [Header("要显示日志的 Text (或 TMP)")]
    public Text debugText;
    [Header("最大行数，超出后自动丢弃最旧")]
    public int maxLines = 100;

    // 存所有行
    private readonly List<string> _logs = new List<string>();
    private TextWriter _defaultConsoleOut;

    // 1. 在最早阶段就开始拦截
    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
    static void InitLogInterceptor() {
        Application.logMessageReceived += HandleStaticLog;
        Application.logMessageReceivedThreaded += HandleStaticLog;
    }

    static void HandleStaticLog(string logString, string stackTrace, LogType type) {
        // 这里是最早阶段的静态缓存。可以存到一个队列里，等 Awake/OnEnable 再显示。
    }

    private void OnEnable() {
        // 主线程日志
        Application.logMessageReceived += HandleLog;
        // 额外再注册一次，多线程日志也能收
        Application.logMessageReceivedThreaded += HandleLog;

        // 2. 把 Console.Write(…) 也重定向过来
        _defaultConsoleOut = Console.Out;
        var redirector = new ConsoleRedirector(_defaultConsoleOut, HandleLogFromConsole);
        Console.SetOut(redirector);
        Console.SetError(redirector);
    }

    private void OnDisable() {
        Application.logMessageReceived -= HandleLog;
        Application.logMessageReceivedThreaded -= HandleLog;
        Console.SetOut(_defaultConsoleOut);
        Console.SetError(_defaultConsoleOut);
    }

    // 处理 Unity 日志回调
    private void HandleLog(string logString, string stackTrace, LogType type) {
        var entry = FormatEntry(logString, stackTrace, type);
        Append(entry);
    }

    // 处理 Console.Write/WriteLine
    private void HandleLogFromConsole(string msg) {
        Append($"[Console] {msg}");
    }

    private string FormatEntry(string msg, string stack, LogType type) {
        switch (type) {
            case LogType.Error:
            case LogType.Exception:
                return $"<color=red>[{type}] {msg}\n{stack}</color>";
            case LogType.Warning:
                return $"<color=yellow>[{type}] {msg}</color>";
            default:
                return $"[{type}] {msg}";
        }
    }

    private void Append(string entry) {
        _logs.Add(entry);
        if (_logs.Count > maxLines)
            _logs.RemoveAt(0);
        debugText.text = string.Join("\n", _logs);
    }

    // 用来接管 System.Console 输出
    class ConsoleRedirector : TextWriter {
        private readonly TextWriter _original;
        private readonly Action<string> _onWrite;
        public ConsoleRedirector(TextWriter original, Action<string> onWrite) {
            _original = original;
            _onWrite  = onWrite;
        }
        public override Encoding Encoding => _original.Encoding;

        public override void Write(string value) {
            _onWrite(value);
            _original.Write(value);
        }
        public override void WriteLine(string value) {
            _onWrite(value + "\n");
            _original.WriteLine(value);
        }
    }
}